#!flask/bin/python
import io
import os
from threading import Lock

from flask import Flask, render_template, render_template_string, request, send_file

from TTS.api import TTS

tts = TTS("tts_models/multilingual/multi-dataset/xtts_v2", gpu=False)

port = 5002

app = Flask(__name__)


@app.route("/")
def index():
    return render_template(
        "index_gauss_2.html"
    )

lock = Lock()

def is_chinese_char(char):
    """判断单个字符是否为中文字符"""
    return '\u4e00' <= char <= '\u9fa5'

def is_all_chinese(text):
    """判断字符串是否全部由中文字符组成"""
    return all(is_chinese_char(c) for c in text)

def contains_chinese(text):
    """判断字符串中是否包含中文字符"""
    return any(is_chinese_char(c) for c in text)

import time
@app.route("/tts/api/tts", methods=["GET", "POST"])
def api_tts():

    start_time = time.time()  # 总耗时起点
    
    # 1. 参数解析阶段
    parse_start = time.time()
    with lock:
        text = request.headers.get("text") or request.values.get("text", "")
        style_wav = request.headers.get("style-wav") or request.values.get("style_wav", "")
        style_wav = f"speaker/{style_wav}-sample.wav"
        parse_time = time.time() - parse_start
        
        print(f" > Model input: {text}")
        
        # 2. TTS生成阶段
        tts_start = time.time()
        if contains_chinese(text):
            wavs = tts.tts(text=text, 
                           speaker_wav=style_wav,
                            language="zh-cn")
        else:
            wavs = tts.tts(text=text, 
                           speaker_wav=style_wav,
                            language="en")
        tts_time = time.time() - tts_start
        
        # 3. 音频处理阶段
        audio_start = time.time()
        out = io.BytesIO()
        tts.synthesizer.save_wav(wavs, out)
        audio_time = time.time() - audio_start
    
    # 计算总耗时
    total_time = time.time() - start_time
    
    # 记录详细耗时日志（可替换为日志系统）
    print(f"[TTS API] 总耗时: {total_time:.3f}s | 参数解析: {parse_time:.3f}s | TTS生成: {tts_time:.3f}s | 音频处理: {audio_time:.3f}s")
    
    # 可选：在响应头中返回耗时信息
    response = send_file(out, mimetype="audio/wav")
    response.headers['X-Process-Time'] = f"{total_time:.3f}s"
    return response


def main():
    app.run(debug=False, host="0.0.0.0", port=port)


if __name__ == "__main__":
    main()
